<?php
class common_run {
	/**
	 * 构造函数
	 */
	public function __construct() {
		// 全局常量
		define('TIME_START_ALL', microtime(true));
		define('ROOT', dirname(dirname(__FILE__)));
		define('VIEW_ROOT', ROOT.'/view');
		define('ACCESS', 1);
		
		// 自动加载机制
		function __autoload($class_name) {
			$class_name_arr = explode('_', $class_name, 2);

            if (count($class_name_arr) < 2)
            {
                $dir = 'library';
                $class_file = strtolower($class_name).'.php';
            }
            else
            {
                $dir = $class_name_arr[0];
                $class_file = $class_name.'.class.php';
            }

			$file_path = ROOT.'/'.$dir.'/'.$class_file;

			if(file_exists($file_path)) {
				require $file_path;		
			} else {
				throw new common_exception('Autoload Class "'.$class_name.'" Error');
			}
		}
		
		// 加载文件
		file_exists(ROOT.'/config/config.php') && require ROOT.'/config/config.php';
		
		// 设置时区 / 启动SESSOIN
		ini_set('date.timezone', 'Asia/Shanghai');
		session_start();
		
		// 接收参数
		$module = empty($_GET['m']) ? 'index' : $_GET['m'];
		$action = empty($_GET['a']) ? 'index' : $_GET['a'];
		define('MODULE', $module);
		define('ACTION', $action);

		// 调用controller
		$controller_class = 'controller_'.$module;
		$controller_action = 'action_'.$action;
		$controller = new $controller_class;
		
		// Before, Action, After
		define('TIME_START_ACTION', microtime(true));
		method_exists($controller, 'before') && $controller->before();
		
		if(method_exists($controller, $controller_action)) {
			$controller->$controller_action();
		} else {
			throw new common_exception('Action "'.ACTION.'" Not Found');
		}
		
		method_exists($controller, 'after') && $controller->after();
		
		//调用view
		define('TIME_START_VIEW', microtime(true));
		$template_path = ROOT.'/view/'.$module.'/'.$action.'.php';
		if(file_exists($template_path)) {
			$controller->display($template_path);
		}
		
		define('TIME_END_ALL', microtime(true));
	}
}
?>
